<template>
    <div class="dropdown" ref="dropdownRef">
        <a href="#" class="btn btn-outline-light my-2 dropdown-toggle" @click.prevent="toggleOpen">
            {{ title }}
        </a>
        <ul class="dropdown-menu" :style="{ display: 'block' }" v-if="isOpen">
            <slot></slot>
        </ul>
    </div>
</template>

<script lang="ts">
// import DropdownItem from './DropdownItem.vue'
import { defineComponent, ref, onMounted, onUnmounted } from 'vue'
export default defineComponent({
    name: 'Dropdown',
    components: {
        // DropdownItem
    },
    props: {
        title: {
            type: String,
            required: true
        }
    },
    setup(props) {
        const titles = ref(props.title)
        const isOpen = ref(false)
        const dropdownRef = ref<null | HTMLElement>(null)

        //打开或关闭下拉栏
        const toggleOpen = () => {
            isOpen.value = !isOpen.value
        }

        //点击下拉栏外部区域关闭下拉栏
        const handler = (e: MouseEvent) => {
            if (dropdownRef.value) {
                if (!dropdownRef.value.contains(e.target as HTMLElement) && isOpen.value) {
                    isOpen.value = false
                }
            }
        }
        onMounted(() => {
            document.addEventListener('click', handler)
        })
        onUnmounted(() => {
            document.removeEventListener('click', handler)
        })


        return {
            isOpen,
            toggleOpen,
            dropdownRef,
            titles
        }
    }
})
</script>

